<template>
    <!--按钮-->
    <div>
        <el-button type="danger" :icon="Plus" @click="SaveBreedingSow">新增</el-button>
        <el-button type="danger" :icon="DocumentAdd">保存</el-button>
        <el-button type="danger" :icon="BottomRight">撤销</el-button>
        <el-button type="danger" :icon="Delete">删除</el-button>
    </div>

    <el-row style="margin-top: 20px;margin-bottom: 20px;">
        <el-col :span="5">
            <el-form-item label="负责人:">
                <el-select v-model="single.principal" placeholder="请选择" clearable>
                    <el-option v-for="user in userList" :key="user.userId" :label="user.userMyName" :value="user.userMyName" />
                </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="5" style="margin-left: 10px;">
            <el-form-item label="妊检日期:">
              <el-date-picker v-model="single.pregnancyTestDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择时间" :size="size"  />
            </el-form-item>
        </el-col>
        <el-col :span="5" style="margin-left:20px;margin-top: 3px;">单据号&nbsp;-- --</el-col>
        <el-col :span="5" style="margin-left: 10px;margin-top: 3px;">流水号&nbsp;-- --</el-col>
    </el-row>
    <hr size="6" style="background-color:rgb(232.8, 233.4, 234.6)">
    <!--表格-->
    <table class="show" style="margin-top: 20px;" border="1">
        <tr align="center">
            <td width="180">序号</td>
            <td width="180">耳号</td>
            <td width="180">妊检结果</td>
            <td width="180">妊检方式</td>
            <td width="180">同胎数</td>
            <td width="180">妊娠天数</td>
            <td width="180">当前栋舍</td>
            <td width="180">当前栏位</td>
            <td width="180">转入栋舍</td>
            <td width="180">转入栏位</td>
        </tr>

        <tr v-for="(item, index) in form" :key="index">
            <!--序号-->
            <td width="180"><el-input :value="index + 1" /></td>
            <!--耳号-->
            <td width="180">
              <el-select v-model="item.basicInforId" placeholder="请选择" @change="handlebedroomField(item.basicInforId,index)" clearable>
                <el-option v-for="basic in basicInforList.filter((x:any)=>x.gender==2 && x.pigTypeId==2 && x.isPrenatalCheckup==1 && x.presentstatus==2)" :key="basic.basicInforId" :label="basic.earNumber" :value="basic.basicInforId" />
              </el-select>
            </td>
            <!--妊检结果-->
            <td width="180">
              <el-select v-model="item.pregnancyTestResultId" placeholder="请选择" clearable>
                <el-option v-for="pregnancyresult in pregnancyResultList" :key="pregnancyresult.pregnancyTestResultId" :label="pregnancyresult.pregnancyTestResultName" :value="pregnancyresult.pregnancyTestResultId" @click="resultCheck(item.pregnancyTestResultId,index)" />
              </el-select>
            </td>
            <!--妊检方式-->
            <td width="180">
              <el-select v-model="item.pregnancyTestTypeId" placeholder="请选择" clearable>
                <el-option v-for="pregnancytype in pregnancyTypeList" :key="pregnancytype.pregnancyTestTypeId" :label="pregnancytype.pregnancyTestTypeName" :value="pregnancytype.pregnancyTestTypeId" />
              </el-select>
            </td>
            <!--同胎数-->
            <td width="180">
              <el-input v-model="item.parityNumber" />
            </td>
            <!--妊娠天数-->
            <td width="180">
              {{ item.gestationDays }}
            </td>
            <!--当前栋舍-->
            <td>{{ item.currentBuilding }}</td>
            <!--当前栏位-->
            <td>{{ item.currentfield }}</td>
            <!--转入栋舍-->
            <td width="180">
              <el-select v-model="item.turnBuilding" placeholder="请选择" @change="handlefield(item.turnBuilding, index)" clearable>
                <el-option v-for="building in bedroomList" :key="building.bedroomId" :label="building.bedroomName" :value="building.bedroomId" />
              </el-select>
            </td>
            <!--转入栏位-->
            <td width="180">
              <el-select v-model="item.turnColumn" placeholder="请选择" clearable>
                <el-option v-for="column in fieldList[index]" :key="column.fieldId" :label="column.fieldName" :value="column.fieldId" />
              </el-select>
            </td>
        </tr>
    </table>
    <!--增行 删行-->
    <div>
      <el-button type="danger" link @click="addRow">+增行</el-button>
      <el-button type="danger" link @click="removeRow" :disabled="form.length <= 0">-删行</el-button>
    </div>

</template>

<script lang="ts" setup>
import { Plus,Delete,DocumentAdd,BottomRight } from '@element-plus/icons-vue'
import {ref,onMounted,reactive} from 'vue'
import axios from 'axios';
import { ElMessage } from 'element-plus';
import {useRouter,useRoute} from 'vue-router'

const apiUrl = import.meta.env.VITE_APP_API_URL;
const apiBedinUrl = import.meta.env.VITE_APPRead_API_URL;

//创建路由实例
const router=useRouter()
const route=useRoute()

const size = ref<'default' | 'large' | 'small'>('default')

//当前时间
const date=new Date();

//响应式数据 获取栋舍
const condition=reactive({
    pageIndex:1,
    pageSize:100,
    bedroomTypeId:0,
    bedroomName:'',
    personName:''
})

//妊检时间
const single=reactive({
    pregnancyTestDate:'',
    principal:'',
})

const form=reactive([{
  prenatalCheckupId: 0,
  documentNumber: "",
  serialNumber: "",
  basicInforId: '',
  pregnancyTestResultId: "",
  pregnancyTestTypeId: '',
  parityNumber: '',
  currentBuilding: "",
  currentfield: "",
  turnBuilding: '',
  turnColumn: '',
  principal: '',
  pregnancyTestDate: '',
  isPrenatalCheckUp: 1,
  createdOwner: localStorage.getItem("userName"),
  createdTime: new Date(),
  updateOwner: '',
  updatedTime: null,
  examineOwner: '',
  examineTime: null,
  //妊娠天数
  gestationDays: '',
}])

//增行 删行
const addRow = () => {
    form.push({
        prenatalCheckupId: 0,
        documentNumber: "",
        serialNumber: "",
        basicInforId: '',
        pregnancyTestResultId: "",
        pregnancyTestTypeId: '',
        parityNumber: '',
        currentBuilding: "",
        currentfield: "",
        turnBuilding: '',
        turnColumn: '',
        principal: '',
        pregnancyTestDate: '',
        isPrenatalCheckUp: 1,
        createdOwner: localStorage.getItem("userName"),
        createdTime: new Date(),
        updateOwner: '',
        updatedTime: null,
        examineOwner: '',
        examineTime: null,
        //妊娠天数
        gestationDays: '',
    })
    console.log(form)
}
const removeRow = () => {
    if (form.length > 0) {
        form.pop()
    }
}

//妊娠天数
const resultCheck=(id:number,index:number)=>{
  if(id==4){
    form[index].gestationDays=Math.ceil((new Date()-new Date(single.pregnancyTestDate))/ (1000 * 3600 * 24))
  }else{
    form[index].gestationDays=0
  }
}

//新增
const SaveBreedingSow=()=>{
    //直接赋值 赋值不到([{}])中  需要使用foreach来进行循环赋值
    form.forEach((item: any) => {
        item.pregnancyTestDate = single.pregnancyTestDate,
        item.principal = single.principal
    })
 console.log(form)
 const obj={
    prenatalCheckups:form
 }
 axios.post(apiBedinUrl+'/api/PrenatalCheckup/CreatePrenatalCheckup',obj)
 .then(res=>{
    if(res.data.code==0){
        ElMessage.success("添加种母妊检成功");

    }else{
        ElMessage.error("添加种母妊检失败");
    }
 })
}

//--------------下拉框---------------//

//获取负责人
const userList=ref([])
const handleprincipal=()=>{
    axios.post(apiUrl+'/api/Users/GetUsers',{
        pageIndex:condition.pageIndex,
        pageSize:condition.pageSize,
    })
    .then(res=>{
        userList.value=res.data.data.list
    })
}

//获取耳号
const basicInforList: any = ref([])
const handlebasicInfor = () => {
    axios.post(apiBedinUrl+'/api/Basics/SearchBasic', {})
    .then(res => {
        console.log(res.data.data)
        basicInforList.value = res.data.data
    })
}

//获取当前栋舍 栏位
const bedroomField:any = reactive({
  gender: '',
  currentbuilding: '',
  currentfield:'',
});
//将该方法放在耳号下拉框 变化的时候将id值与下标传过来了
const handlebedroomField = (id:number,index:number) => {
  axios.post(apiBedinUrl+"/api/Basics/SearchBedroomField", {
    //根据耳号id进行获取
    basicInforId:id
  }).then((res) => {
    console.log(res.data.data)
    //给栋舍 栏位 性别赋值
    bedroomField.gender=res.data.data.gender;
    bedroomField.currentbuilding=res.data.data.bedroomName;
    bedroomField.currentfield=res.data.data.fieldName;
    //根据下标进行赋值
    form[index].currentBuilding=bedroomField.currentbuilding;
    form[index].currentfield=bedroomField.currentfield;
  });
};

//获取妊检结果
const pregnancyResultList:any=ref([])
const handlePregnancyResult=()=>{
    axios.get(apiBedinUrl+'/api/PrenatalCheckup/SearchPregnancyResult',{})
    .then(res=>{
        pregnancyResultList.value=res.data.data
    })
}

//获取妊检方式
const pregnancyTypeList:any=ref([])
const handlePregnancyType=()=>{
    axios.get(apiBedinUrl+'/api/PrenatalCheckup/SearchPregnancyType',{})
    .then(res=>{
        pregnancyTypeList.value=res.data.data
    })
}

//获取栋舍
const bedroomList:any=ref([])
const handleBedroom=()=>{
    axios.post(apiUrl+'/api/BedRoom/ShowBedroom',{
        pageIndex: condition.pageIndex,
        pageSize: condition.pageSize,
        bedroomTypeId: condition.bedroomTypeId,
        bedroomName: condition.bedroomName,
        personName:condition.personName
    }).then(res=>{
        bedroomList.value=res.data.data.list
    })
}

//获取栏位
const fieldList:any=ref([])
const handlefield=(id:number,index:number)=>{
    form[index].turnColumn=''
    axios.post(apiUrl+'/api/BedRoom/GetBrdroomIdField',{
        bedroomId:id
    }).then(res=>{
        fieldList.value[index]=res.data.data
    })
}

//创建生命周期函数钩
onMounted(()=>{
    handleprincipal()//负责人
    handlebasicInfor()//耳号
    handlePregnancyResult()//妊检结果
    handlePregnancyType()//妊检方式
    handleBedroom()
})
</script>

<style>
.show {
  border-collapse: collapse;
  border-top: 2px solid red; /* 设置上边框为红色 */
}
</style>
